<template>
  <div class="content">
    <div class="top-content">
      <span class="money">账户金额 <span>(<span style="font-weight:600;font-size:18px">{{ queryParam.provide
            }}</span>)</span> </span>
      <div class="ye">
        <span>可用余额 ( 元 ) </span>
        <span>{{ formatNumber(parseFloat(moneyAll)) }}</span>
      </div>
      <div class="center-content">
        <span>账户信息</span>
        <div class="text-tab">
          <div class="kpzh">
            <div class="kp">
              <span style="font-size:20px;font-wight:600">中心库</span>
            </div>
            <div v-for="item in centerWarehouse" :key="item.id">
              <span style="display:flex;justify-content: space-between;">
                <div style="display:flex;justify-content: space-between;width:45%">
                  <span style="display:inline-block;">
                    {{ item.productGroup }}({{ item.company }})：
                  </span>
                  <span class="Num" style="display:inline-block;margin-left:auto;">{{
        formatNumber(parseFloat(item.moeny))
      }}</span>
                </div>

                <el-button size="mini" type="text" class="icon-button" icon="el-icon-edit-outline"
                  @click="makeOutAnInvoice(item)">开票</el-button>
              </span>
            </div>
          </div>
          <div class="kpzh">
            <div class="kp">
              <span style="font-size:20px;font-wight:600">平台配件库</span>
            </div>

            <div v-for="item in accessoryWarehouse" :key="item.id">
              <span style="display:flex;justify-content: space-between;">
                <div style="display:flex;justify-content: space-between;width:35%">
                  <span style="display:inline-block;">{{ item.productGroup }}：</span>
                  <span class="Num" style="display:inline-block;margin-left:auto;">{{
        formatNumber(parseFloat(item.moeny)) }}</span>
                </div>
                <el-button size="mini" type="text" class="icon-button" icon="el-icon-edit-outline"
                  @click="makeOutAnInvoice(item)">开票</el-button>
              </span>
            </div>
          </div>
        </div>

      </div>
    </div>
    <div class="bottom-content">
      <div style="  display: flex;">
        <div class="accounts" style="width:28%">
          <span>筛选：</span>
          <el-button :class="{ active: kpType === 'all' }" class="all" size="mini"
            @click="handleAccountButtonClick('all')">全部</el-button>
          <el-button :class="{ active: kpType === 'sr' }" class="sr" size="mini"
            @click="handleAccountButtonClick('sr')">入账</el-button>
          <el-button :class="{ active: kpType === 'zc' }" class="zc" size="mini"
            @click="handleAccountButtonClick('zc')">开票</el-button>
          <el-button :class="{ active: kpType === 'zf' }" class="zf" size="mini"
            @click="handleAccountButtonClick('zf')">作废</el-button>
        </div>
        <div class="accounts" style="width:30%">
          <el-button :class="{ active: companyType === 'all' }" class="all" size="mini"
            @click="companyTypeButtonClick('all')">全部</el-button>
          <el-button :class="{ active: companyType === 'yy' }" class="yy" size="mini"
            @click="companyTypeButtonClick('yy')">营运公司</el-button>
          <el-button :class="{ active: companyType === 'js' }" class="js" size="mini"
            @click="companyTypeButtonClick('js')">金山巴士</el-button>
          <el-button :class="{ active: companyType === 'cm' }" class="cm" size="mini"
            @click="companyTypeButtonClick('cm')">崇明巴士</el-button>
        </div>
        <div class="date" style="width:20%">
          <el-button :class="{ active: dateType === 'all' }" class="all" size="mini"
            @click="handleDateButtonClick('all')">近7日</el-button>
          <el-button :class="{ active: dateType === 'sr' }" class="sr" size="mini"
            @click="handleDateButtonClick('sr')">近30日</el-button>
          <el-button :class="{ active: dateType === 'zc' }" class="zc" size="mini"
            @click="handleDateButtonClick('zc')">自定义</el-button>
        </div>
        <el-date-picker clearable v-model="dateTime" :disabled="disabledDate" type="datetimerange"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择搜索时间"
          @change="handleDateChange">
        </el-date-picker>
      </div>
      <div>
        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column prop="invoiceTime" label="财务时间" width="180" align="center">
          </el-table-column>
          <el-table-column prop="company" label="所属公司" width="180" align="center">
          </el-table-column>
          <el-table-column prop="provideType" label="类型" width="130" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.provideType === '开票'">{{ scope.row.provideType }}</span>
              <span v-if="scope.row.provideType === '入账'"> <i class="el-icon-notebook-2"></i> {{ scope.row.provideType
                }}</span>
              <div v-if="scope.row.provideType === '作废'" class="DataCenter">
                <el-image :src="zffpImg" class="zffpImg"></el-image>
                <span class="text1">{{ scope.row.provideType }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="provideMoney" label="金额 (元) " align="center" width="197">
            <template slot-scope="scope">
              <span style="float: right;">{{ formatNumber(parseFloat(scope.row.provideMoney)) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="balanceMoney" label="余额 (元) " align="center" width="197">
            <template slot-scope="scope">
              <span style="float: right;">{{ formatNumber(parseFloat(scope.row.balanceMoney)) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.provideType === '开票'">开票编码:{{ scope.row.remark }} ({{ scope.row.provideWare }}{{
        scope.row.provideGroup }})</span>
              <span v-if="scope.row.provideType === '作废'">开票编码:{{ scope.row.remark }} ({{ scope.row.provideWare }}{{
        scope.row.provideGroup }})-{{ scope.row.provideType }}</span>
              <span v-if="scope.row.provideType === '入账'">{{ scope.row.remark }}</span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page.sync="queryParam.pageNum" :page-size="queryParam.pageSize" layout="total, prev, pager, next"
          :total="total" align="right">
        </el-pagination>
      </div>
    </div>

    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :center="true"
      :before-close="handleClose" :show-close="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商" prop="provide">
              <el-input v-model="form.provide" placeholder="请输入供应商" :disabled="visibleShow" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属公司" prop="productWare">
              <el-input v-model="form.company" placeholder="请输入所属公司" :disabled="visibleShow" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属仓库" prop="productWare">
              <el-input v-model="form.productWare" placeholder="请输入所属仓库" :disabled="visibleShow" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="productGroup">
              <el-input v-model="form.productGroup" placeholder="请输入类型" :disabled="visibleShow" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="金额" prop="money">
              <el-input v-model="form.money" placeholder="请输入金额" />
              <span style="color:red">余额：{{ formatNumber(parseFloat(this.money)) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票编码" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入开票编码后四位"   maxlength="4"  />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { invoicingList, flowList, flowInvoicing, checkInvoicing } from '@/api/system/supplierBillingDetail'
import { roundToDecimals,addroundToDecimals }  from "@/utils/mathCalculation.js"
export default {
  data() {
    return {
      zffpImg: require('../../../assets/icon/zffp.png'),
      dateTime: [],
      dateType: 'all', // 默认选中的日期类型
      kpType: 'all',
      companyType: 'all',
      tableData: [],
      centerWarehouse: [],
      accessoryWarehouse: [],
      moneyAll: 0,
      disabledDate: true,
      queryParam: {
        provide: '',
        startTime: '',
        endTime: '',
        provideType: '',
        company: "",
        pageNum: 1,
        pageSize: 5
      },
      total: 0,
      deptName: '',
      title: '供应商开票',
      open: false,
      rules: {
        money: [
          { required: true, message: '请输入金额', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入备注', trigger: 'blur' }
        ]
      },
      form: {
        money: "",
        company: "",
        productGroup: "",
        productWare: "",
        provide: ""
      },
      money: 0,
      visibleShow: false,
      loading: false,
      id: "",
    }
  },
  created() {
    // dateTime初始化值
    const endDate = new Date();
    endDate.setHours(23, 59, 59, 999); // 设置结束时间为当天的23:59:59
    const startDate = new Date();
    startDate.setDate(endDate.getDate() - 7);
    startDate.setHours(0, 0, 0, 0); // 设置开始时间为7天前的00:00:00
    this.dateTime = [startDate, endDate];
    // 角色权限判定
    const User = localStorage.getItem('User');
    this.deptName = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';
    if (this.deptName !== '物资公司') {
      this.queryParam.provide = this.deptName;
    } else {
      this.queryParam.provide = this.deptName;
    }
    this.flowList(); // 刷新函数
    this.getList();

  },

  methods: {
    handleClose(done) {

      done(false); // 不允许关闭

    },
    // 金额接口
    getList() {
      this.moneyAll = 0;
      // 初始化中心库和配件库数组
      this.centerWarehouse = [];
      this.accessoryWarehouse = [];
      invoicingList(this.queryParam.provide).then(rst => {
        if (rst.code === 200) {
          rst.data.forEach(item => {
            // 根据productWare属性将对象分别放入中心库和配件库数组
            if (item.productWare === '中心库') {
              this.centerWarehouse.push(item);
            } else if (item.productWare === '配件库') {
              this.accessoryWarehouse.push(item);
            }
            // 开票检查失败后重新赋值
            if (item.productWare === this.form.productWare && item.provide === this.form.provide &&
              item.productGroup === this.form.productGroup && item.company === this.form.company
            ) {
              this.money = item.moeny;
              this.form.uuid = item.uuid===null?"":item.uuid

            }
            // 将money相加得到总金额
            // this.moneyAll += parseFloat(item.moeny);
            this.moneyAll = addroundToDecimals(this.moneyAll, parseFloat(item.moeny))
          });
        }
      })
    },
    // 列表接口
    flowList() {

      if (this.dateTime && this.dateTime.length === 2) {
        // 日期格式转换
        const formatDate = date => {
          const newDate = new Date(date); // 创建一个新的 Date 对象
          const year = newDate.getFullYear();
          const month = String(newDate.getMonth() + 1).padStart(2, '0');
          const day = String(newDate.getDate()).padStart(2, '0');
          const hours = String(newDate.getHours()).padStart(2, '0');
          const minutes = String(newDate.getMinutes()).padStart(2, '0');
          const seconds = String(newDate.getSeconds()).padStart(2, '0');
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        };
        const startDate = new Date(this.dateTime[0]);
        const endDate = new Date(this.dateTime[1]);

        this.queryParam.startTime = formatDate(startDate);
        this.queryParam.endTime = formatDate(endDate);
        this.dateTime = [this.queryParam.startTime, this.queryParam.endTime]
      } else {
        this.queryParam.startTime = "";
        this.queryParam.endTime = "";
      }
      flowList(this.queryParam).then(rst => {
        if (rst.code === 200) {
          this.tableData = rst.rows;
          this.total = rst.total

        }
      })
    },
    // 分页change事件
    handleSizeChange(val) {
      this.queryParam.pageSize = val;
      this.flowList();
    },
    handleCurrentChange(val) {
      this.queryParam.pageNum = val;
      this.flowList();
    },
    //  数字转换格式
    formatNumber(value) {
      // if (value) {
      //   let [integerPart, decimalPart] = value.toString().split('.');
      //   let formattedNumber = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + '.' + decimalPart.slice(0, 3);
      //   return formattedNumber;
      // }
      if(value) {
        return roundToDecimals(value, 2)
      } else {
        return "0.00"
      }
    },
    // 开票类型搜索
    handleAccountButtonClick(type) {
      if (type === 'all') {
        this.queryParam.provideType = ''
      } else if (type === 'sr') {
        this.queryParam.provideType = '入账'
      } else if (type === 'zc') {
        this.queryParam.provideType = '开票'
      } else if (type === 'zf') {
        this.queryParam.provideType = '作废'
      }
      this.kpType = type; // 更新选中的日期类型
      this.flowList(); // 刷新函数
    },
    companyTypeButtonClick(type) {
      if (type === 'all') {
        this.queryParam.company = ''
      } else if (type === 'yy') {
        this.queryParam.company = '营运公司'
      } else if (type === 'js') {
        this.queryParam.company = '金山巴士'
      } else if (type === 'cm') {
        this.queryParam.company = '崇明巴士'
      }
      this.companyType = type; // 更新选中的日期类型
      this.flowList(); // 刷新函数
    },
    // 日期时间搜索
    handleDateButtonClick(type) {
      if (type === 'all') {
        this.dateTime = [];
        this.disabledDate = true;
        // 设置日期为近7日
        const endDate = new Date();
        endDate.setHours(23, 59, 59, 999); // 设置结束时间为当天的23:59:59
        const startDate = new Date();
        startDate.setDate(endDate.getDate() - 7);
        startDate.setHours(0, 0, 0, 0); // 设置开始时间为7天前的00:00:00
        this.dateTime = [startDate, endDate];
      } else if (type === 'sr') {
        this.dateTime = [];
        this.disabledDate = true;
        // 设置日期为近30日
        const endDate = new Date();
        endDate.setHours(23, 59, 59, 999); // 设置结束时间为当天的23:59:59
        const startDate = new Date();
        startDate.setDate(endDate.getDate() - 30);
        startDate.setHours(0, 0, 0, 0); // 设置开始时间为30天前的00:00:00
        this.dateTime = [startDate, endDate];
      } else if (type === 'zc') {
        // 自定义日期，可以根据需求进行处理
        this.dateTime = [];
        this.disabledDate = false;
      }
      this.dateType = type; // 更新选中的日期类型
      this.flowList(); // 刷新函数
    },
    // 日期change事件
    handleDateChange() {
      this.flowList(); // 每次日期组件值改变时刷新函数
    },
    reset() {
      this.form = {
        productGroup: "",
        productWare: "",
        provide: "",
        remark: "",
        money: ""
      };
      this.resetForm("form");
    },
    // 开票
    makeOutAnInvoice(row) {
      this.money = row.moeny=== null ? "" : row.moeny;
      this.visibleShow = true;
      this.form.company = row.company=== null ? "" : row.company;
      this.form.productGroup = row.productGroup=== null ? "" : row.productGroup;
      this.form.productWare = row.productWare=== null ? "" : row.productWare;
      this.form.provide = row.provide=== null ? "" : row.provide;
      this.open = true;
      this.id = row.id=== null ? "" : row.id;
      this.form.uuid = row.uuid=== null ? "" : row.uuid;
    },

    
    //开票确认
    async submitForm() {
      await this.$refs["form"].validate(valid => {
        if (valid) {
          checkInvoicing(this.id, this.form.uuid).then(rst => {
            if (rst.code === 200) {
              this.flowInvoicing();
            } else {
              this.getList();
              this.form.money="";
              this.form.remark="";
              this.$message.error('数据已改变，请重新输入金额与编码')
            }
          })
        }
      })

    },

    flowInvoicing() {
      let moneyNumeric = parseFloat(this.money);
      let formMoneyNumeric = parseFloat(this.form.money);

      if (formMoneyNumeric <= moneyNumeric &&this.form.money>0) {
        this.loading = true;
        flowInvoicing(this.form.money,this.form.company,this.form.provide,this.form.productGroup,this.form.productWare,this.form.uuid,this.form.remark).then(rst => {
          if (rst.code === 200) {
            this.open = false;
            this.$message({
              type: 'success',
              message: rst.msg
            });
            this.reset();
            this.getList();
            this.flowList(); // 刷新函数
            this.loading = false;
          } else {
            this.getList();
            this.form.money="";
            this.form.remark="";
            this.$message({
              type: 'error',
              message: '数据已改变，请重新输入金额与编码'
            });
            this.loading = false;
          }

        })
      } else {
        this.$message({
          type: 'error',
          message: '输入金额大于余额或小于0请重新输入'
        });
      }
    },

    //  开票取消
    cancel() {
      this.open = false;
      this.reset();
      this.loading = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  width: 100% !important;
  height: 100% !important;
  background-color: #F5F7FA !important;
  padding-top: 20px;
}

.top-content {
  width: 70%;
  margin: auto;
  padding: 15px 15px 0px 20px;
  background-color: white;
  font-size: 15px;
  color: #292929;

  .money {
    display: inline-block;
    margin-bottom: 15px;
  }

  .ye {
    span {
      display: block;
      margin-bottom: 10px;
    }

    span:nth-child(2) {
      font-weight: 600;
      font-size: 28px;
    }
  }

  .center-content {
    margin: 20px 0;

    .text-tab {
      display: flex;

    }


    .kpzh {
      width: 600px;
      height: 200px;
      margin-right: 10px;
      background-color: #F5F7FA !important;
      line-height: 30px;
      padding: 20px 20px;
      margin-top: 20px;
      margin-bottom: 5px;
      overflow-y: scroll;



      span {
        display: block;

        .Num {
          font-weight: 600;
          font-size: 18px;
          display: inline-block;
        }
      }

      .kp {
        display: flex;
        justify-content: space-between;
      }

    }

  }

  .icon-button {
    font-size: 14px;
    float: right;
  }


}

.el-icon-notebook-2 {
  color: #409EFF;
}

.bottom-content {
  width: 70%;
  height: 30%;
  margin: auto;
  padding: 15px 15px 0px 20px;
  background-color: white;


  ::v-deep .el-table__row {
    height: 53px;
  }

  .active {
    background-color: #409EFF;
    /* 设置选中状态的背景颜色 */
    color: #fff;
    /* 设置选中状态的文字颜色 */
  }

  .accounts,
  .date {
    .el-button {
      margin-left: 0px !important;
    }

    .sr,
    .zc,
    .yy,
    .js,
    .cm,
    .zf {
      border-left: 0px !important;
      border-top-left-radius: 0;
      /* 右上角变为直角 */
      border-bottom-left-radius: 0;
      /* 右下角变为直角 */
    }

    .all,
    .sr,
    .yy,
    .js,
    .zc {
      border-top-right-radius: 0;
      /* 右上角变为直角 */
      border-bottom-right-radius: 0;
      /* 右下角变为直角 */
    }
  }

  ::v-deep .el-date-editor {
    height: 27.6px !important;
    margin-left: 20px;

  }

  ::v-deep .el-range-separator {
    margin-bottom: 10px !important;
  }

  ::v-deep .el-input__icon {
    margin-bottom: 10px !important;
  }

  .el-table {
    height: 380px;
    margin-top: 20px;
  }

  .el-pagination {
    margin-top: 10px;


  }
}

.zffpImg {
  width: 17px;
  height: 17px;
}

.DataCenter {
  display: flex;
  justify-content: center;
  align-items: center;
}

.text1 {
  margin-top: 2px;
  margin-left: 5px;
}
</style>
